package com.prs.crm.mail;

import java.util.Properties;
import java.util.regex.Pattern;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeMessage.RecipientType;

import org.courser.Util;

import com.prs.crm.domain.Attachment;
import com.prs.crm.domain.oa.MailBox;
import com.prs.crm.domain.oa.MailItem;
import com.prs.crm.domain.sys.MailAddress;
import com.prs.crm.exception.InValidException;
import com.sun.istack.internal.FinalArrayList;
public class MailSenderImpl implements MailSender {
	public void sendMail(MailItem item)
	{
		final MailBox box = item.getMailBox();
		MailAddress addr = box.getAddr();
		int port = (box.getAddr().getSmtpPort()==null)?25:box.getAddr().getSmtpPort();
		
		Properties props = System.getProperties();
        props.put("mail.smtp.user", box.getUserName());
        props.put("mail.smtp.user.password", box.getPassWord());
        props.put("mail.smtp.host", box.getAddr().getSmtp());
        props.put("mail.smtp.port", port);
        props.put("mail.smtp.socketFactory.port", port);
        props.put("mail.smtp.auth", "true");
        if (addr.getSmtpTls()!=null && addr.getSmtpTls().booleanValue())
        {
        	props.put("mail.smtp.starttls.enable","true");
        }
       
        if (box.getAddr().getAuth()!=null 
				&& box.getAddr().getAuth().booleanValue())
        {
        	props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        	props.put("mail.smtp.socketFactory.fallback", "false");
        }
        
        Session session = Session.getInstance(props, new Authenticator()
        {
        	public PasswordAuthentication getPasswordAuthentication()
            {
                return new PasswordAuthentication(box.getUserName(), box.getPassWord());
            }
        });
        try
        {
	        MimeMessage msg=new MimeMessage(session);   
	        msg.setSentDate(Util.nowFullTime());   
	        msg.setSubject(item.getTitle());   
	        msg.setFrom(new InternetAddress(box.getUserName()));
	        Pattern p = Pattern.compile("[,|，|;|；]");
			String[] recivers = p.split(item.getSendTo());
			for (String reciver : recivers)
			{
				msg.addRecipient(RecipientType.TO,new InternetAddress(reciver));
			}
	        MimeBodyPart body=new MimeBodyPart();   
           // textBodyPart.setText(item.getContent());
	        body.setDataHandler(new DataHandler(item.getContent(),   
            "text/html;charset=UTF-8"));
            Multipart container=new MimeMultipart("related");   
            container.addBodyPart(body);   
            if(item.getAttachs()!=null)   
            {   
                for(Attachment attach : item.getAttachs()) 
                {   
                    MimeBodyPart fileBodyPart=new MimeBodyPart();   
                    FileDataSource fds = new FileDataSource(attach.getPath());   
                    fileBodyPart.setDataHandler(new DataHandler(fds));   
                    fileBodyPart.setFileName("=?GBK?B?"  
                            + new sun.misc.BASE64Encoder().encode(attach.getName().getBytes())   
                            + "?=");   
                    container.addBodyPart(fileBodyPart);   
                }   
            }   
            msg.setContent(container);   
            Transport.send(msg);    
        }
        catch (Exception e)
        {
        	e.printStackTrace();
        	throw new InValidException(e.getMessage());
        }
	}
}

